//
//  FoeumSearchViewController.m
//  HubeiHotel
//
//  Created by LiBenCan on 17/11/16.
//  Copyright © 2017年 张露杰. All rights reserved.
//

#import "FoeumSearchViewController.h"
#import "BaseMBView.h"
#import "ForumCell.h"
#import "ForumDetailViewController.h"
@interface FoeumSearchViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>

@property (nonatomic, strong) UITableView *table;
@property (nonatomic,strong)NSString *serchStr;//搜索的内容
@property (nonatomic,strong) NSMutableArray *datas;//数据
@property (nonatomic,assign) NSInteger pageNumber;//页码

@end

@implementation FoeumSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _serchStr = @"";
    _pageNumber = 1;
    _datas = [NSMutableArray new];
    [self initSearchBarWithPlaceholder:@"请输入搜索的用户名" showsCancelButton:NO];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 20*screenW_6, 15*screenW_6);
    [btn addTarget:self action:@selector(onTapLeftBarButton) forControlEvents:UIControlEventTouchUpInside];
    [btn addSubview:[TomamaUI createImageView:CGRectMake(0, 0, 9*screenW_6, 15*screenW_6) backGroundImageV:@"back"]];
    UIBarButtonItem *barButtonitem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = barButtonitem;
    
    UITextField *inputFiled = [self.baseSesearchBar valueForKey:@"_searchField"];
    [inputFiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.table];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.baseSesearchBar endEditing:YES];
}

#pragma mark - SearchBarDelegate

-(void)textFieldDidChange:(UITextField *)textField
{
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    if (!position) {//输入的实体字 搜索
        
    }
    _serchStr = textField.text;
}

-(UITableView *)table//创建TableV
{
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0,0, SCREENW, SCREENH - 49) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.showsHorizontalScrollIndicator = NO;
        _table.showsVerticalScrollIndicator = NO;
        _table.separatorStyle = 0;
        _table.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
        //刷新
        _table.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            _pageNumber = 1;
            [_datas removeAllObjects];
            [_table.mj_footer resetNoMoreData];
            [self getList];
        }];
        //加载
        _table.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            _pageNumber ++;
            [self getList];
        }];
    }
    return _table;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _datas.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ForumCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ForumCell"];
    if (cell == nil) {
        cell = [[ForumCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ForumCell"];
    }
    //    [cell setDataDic:_datas[indexPath.section] IsDetail:NO];
    [cell loadCellWithData:_datas[indexPath.section]];
    __weak typeof(self) weakSelf = self;
    cell.commentTapBlock = ^(NSInteger index){
        if (index == 0) {
            
        }else if (index == 1){
            NSMutableDictionary *post = weakSelf.datas[indexPath.section];
            if ([post[@"isClick"] boolValue]) {
                [TomamaUI creatAlertWithTarget:weakSelf message:@"已点过赞" timeInterval:2];
            }else{
                [post setObject:@"1" forKey:@"isClick"];
                [post setObject:[NSString stringWithFormat:@"%ld",[post[@"clickNum"] integerValue] + 1>0?[post[@"clickNum"] integerValue] + 1:0] forKey:@"clickNum"];
                [weakSelf.datas replaceObjectAtIndex:indexPath.section withObject:post];
                [tableView reloadData];
                [weakSelf clickPostWithIndex:indexPath.section];
            }
        }
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat h;
    h += [TomamaUI getStringHeightWith:_datas[indexPath.section][@"content"] andWeith:SCREENW - 30*screenW_6 andFont:[UIFont systemFontOfSize:14*screenW_6]];
    NSArray *imags = _datas[indexPath.section][@"imgList"];
    if (imags.count) {
        h += 175*screenW_6;
    }
    return h + 105*screenW_6;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= _datas.count) {
        return;
    }
    ForumDetailViewController *vc = [ForumDetailViewController new];
    vc.postId = _datas[indexPath.section][@"id"];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - searchDelegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (![TomamaUI isNotNullStr:[[searchBar.text componentsSeparatedByString:@" "] componentsJoinedByString:@""]]) {
        return;
    }
    NSMutableArray *array = [NSMutableArray arrayWithArray:[standfault objectForKey:@"searchHistory"]];
    if (!array) {
        array = [NSMutableArray array];
    }
    if (![array containsObject:searchBar.text]) {
        [array addObject:searchBar.text];
        [standfault setObject:array forKey:@"searchHistory"];
        [standfault synchronize];
        [_table reloadData];
    }
    [_datas removeAllObjects];
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    [self getList];
    [searchBar resignFirstResponder];
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    HBHBackView *view;
    if ([self.view viewWithTag:100]) {
        view = (id)[self.view viewWithTag:100];
    }else{
        view = [[HBHBackView alloc] init];
        view.tag = 100;
    }
    view.blcok = ^(){
        [searchBar resignFirstResponder];
    };
    [self.view addSubview:view];
    return YES;
}

-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    UIView *view = [self.view viewWithTag:100];
    [view removeFromSuperview];
    _serchStr = searchBar.text;
    return YES;
}

#pragma mark - request
-(void)getList
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/post/postList" Dic:@{@"jdUserId":[Storage getToken],@"isHot":_isHot,@"pageNo":[NSString stringWithFormat:@"%ld",_pageNumber],@"pageSize":@"10",@"nickName":_serchStr} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper hideHudToView:self.view];
                if ([responseDic[@"success"] boolValue]) {
                    if (_datas.count < [responseDic[@"count"] integerValue]) {
                        [_datas addObjectsFromArray:responseDic[@"data"]];
                    }
                }else{
                    [TomamaUI creatAlertWithTarget:self message:responseDic[@"msg"] timeInterval:2];
                }
                [_table reloadData];
                if ([_table.mj_header isRefreshing]) {
                    [_table.mj_header endRefreshing];
                }
                if ([_table.mj_footer isRefreshing]) {
                    if (_datas.count < [responseDic[@"count"] integerValue]) {
                        [_table.mj_footer endRefreshing];
                    }else{
                        [_table.mj_footer endRefreshingWithNoMoreData];
                    }
                }
            });
        }];
    });
}

-(void)clickPostWithIndex:(NSInteger)index
{
    NSMutableDictionary *post = [NSMutableDictionary dictionaryWithDictionary:_datas[index]];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/post/clickPost" Dic:@{@"post.id":post[@"id"],@"user.id":[Storage getToken]} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([responseDic[@"success"] boolValue]) {
                    
                }else{
                    [post setObject:@"0" forKey:@"isClick"];
                    [post setObject:[NSString stringWithFormat:@"%ld",[post[@"clickNum"] integerValue] - 1>0?[post[@"clickNum"] integerValue] - 1:0] forKey:@"clickNum"];
                    [_datas replaceObjectAtIndex:index withObject:post];
                    [_table reloadData];
                }
            });
        }];
    });
}

@end
